<?php

namespace oa\models;

use Yii;

class LogUserVisit extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'log_user_visit';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'uid' => 'Uid',
            'router' => 'Router',
            'router_name' => 'Router Name',
            'exec_msec' => 'Exec Msec',
            'ip' => 'Ip',
            'server_data' => 'Server Data',
            'visit_at' => 'Visit At',
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => \yii\behaviors\TimestampBehavior::className(),
                'attributes' => [
                    \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['created_at']
                ],
            ], [
                'class' => \yii\behaviors\AttributeBehavior::className(),
                'attributes' => [
                    \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => 'ip',
                ],
                'value' => function ($event) {
                    return Yii::$app->request->getUserIP();
                },
            ], [
                'class' => \yii\behaviors\AttributeBehavior::className(),
                'attributes' => [
                    \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => 'server_data',
                ],
                'value' => function ($event) {
                    return json_encode($_SERVER);
                },
            ], [
                'class' => \yii\behaviors\AttributeBehavior::className(),
                'attributes' => [
                    \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => 'uid',
                ],
                'value' => function ($event) {
                    return Yii::$app->user->isGuest ? 0 : Yii::$app->user->id;
                },
            ],
        ];
    }
}
